<?php
namespace app\api\controller;

use think\Cache;
use app\api\model\UserModel;
use think\Controller;
use think\Request;
use app\conmon\WXBizDataCrypt;
use think\Db;
require_once('SmsTools.php');

class User extends Controller
{
   /**
    * 用户类
    *
    * 我的订单  type = 0:全部  -1:关闭  1:待付款  2:待收货  3:已完成
    */
//    public function login(Request $request){
//        $goodsid = $request->post();
//        UserModel::instance()->login_data($goodsid);
//
//    }
    public function logins(){
        $content = file_get_contents ( 'php://input' );
        $content=json_decode($content,true);
        // $utoken=$content["utoken"];
        // if(!empty($utoken)&&Cache($utoken)){
        //     $result["success"]=11;
        //     $result['utoken']=$utoken;
        //     echo json_encode($result);
        //     return;
        // }
        $code=$content["code"];
        $bid = $content["bid"];
        $encryptedData=$content["encryptedData"];
        $iv = $content['iv'];
        /*获取session_key*/
        $s_result=$this->getSession($code,$bid);
        $WxData = new WXBizDataCrypt($s_result['appid'],$s_result['session_key']);
        /*解密用户数据*/
        $errCode = $WxData->decryptData($encryptedData, $iv, $user_data);
       // $wxap_key = md5(uniqid(md5(microtime(true)),true));
        $result=array();
        if($errCode==0){
            $user_data=json_decode($user_data,true);
            $result["success"]=10;
          //  $result['utoken']=$wxap_key;
            $result['openid'] = $s_result['openid'];
            $user_id = $this->wxUserAdd($user_data,$bid);
//            $result['uid'] = $user_id['uid'];
            if($user_id < 1 || empty($user_id)){
                $result["success"]=-1;
                $result['errCode']=0;
                $result['msg']="获取用户信息出错！";
                echo json_encode($result);
                return;
            }
            $user_data['uid']=$user_id;
            //var_dump($user_data['uid']);
            //Cache::set($wxap_key,$user_data,7200);
            echo  json_encode($result);
            return;
        }else{
            $result["success"]=-1;
            $result['errCode']=$errCode;
            $result['msg']="获取用户信息出错！！";
            echo json_encode($result);
            return;
        }
    }

    /*code 换取 session_key*/
    public function getSession($code,$bid) {
        $loginId  = Db::name('business')->where(['bid'=>$bid])->field('appid,secret')->find();

        $s_data['appid'] = $loginId['appid'];
        $s_data['secret'] = $loginId['secret'];
        $s_data['js_code'] = $code;
        $s_data['grant_type']="authorization_code";
        $session_url = 'https://api.weixin.qq.com/sns/jscode2session?'.http_build_query ( $s_data );
        // echo $session_url.'<br/>';
        $content = file_get_contents ( $session_url );
        // echo $content;
        $content = json_decode ( $content, true );
        $content['appid']=$s_data['appid'];
        return $content;
    }
    public function wxUserAdd($data,$bid){

        $t_user = db('user');
        $data1['openid'] = $data['openId'];
        //var_dump($data);
        //echo 1;
        //var_dump($user_info['user_id']);
        if($user_info = $t_user->where('openid',$data1['openid'])->find()){
            $data2['nickname'] = $data['nickName'];
            $data2['head'] = $data['avatarUrl'];
            $insert = $t_user->where('openid',$data1['openid'])->update($data2);
            return $user_info['uid'];
        }
        // if($user_info = $t_user->where('openid',$data1['openid'])->find())
        //echo 1;
        $data1['bid'] = $bid;
        $data1['nickname'] = $data['nickName'];
        $data1['sex'] = $data['gender'];
//        $data1['language'] = $data['language'];
        $data1['address'] = $data['city'];
//        $data1['province'] = $data['province'];
        $data1['head'] = $data['avatarUrl'];
        $data1['regtime'] = time();
        $data1['status'] = 1;
        //$insert_id =
        if($insert_id=$t_user ->insert($data1)){
            return  $insert_id;
        }else{
            return 0;
        }

    }
    public function getUid() {
        $openid = input('param.openid');
//        var_dump($openid);
        if(empty(input('param.openid'))){
            echo json_encode(['data'=>'没有获取权限']);
        }else{
            $loginId  = Db::name('user')->where('openid',$openid)->field('uid,phone,head')->find();
           echo json_encode(['data'=>$loginId['uid'],'phone'=>$loginId['phone'],'head'=>$loginId['head']]);
        }
    }
    public function reg()
    {
        $arr = input('param.');
        $phone = db('user')->field('phone')->select();

        $arrs = [
            'phone' => $arr['phone'],
            'updatetime' => time()
        ];
        if ($res = db('user')->where('uid',$arr['uid'])->update($arrs)) {
            echo json_encode(['res' => 1,'phone'=>$arr['phone']]);
        }
    }
    public function checkcode (){
        //引入短信验证码
        require_once "SmsSender.php";
        $phone = input('param.phone');
        $phones = db('user')->field('phone')->select();
        $test = 1;
        foreach ($phones as $k=>$v) {
            if( $phone === $v['phone']){
              $test=0;
            }
        }
        if($test == 0){
            echo json_encode(['res'=>0]);
        }
        //实例化
        if($test != 0){
            $sms = controller('Regist', 'controller');
            header("Content-type:text/html;charset=utf-8");
            $code = rand(1000, 9999);

            $str = "您好，你的验证码为code1，请于2分钟内填写。如非本人操作，请忽略本短信。";
            $strs = str_replace('code1', $code, $str);
            //发送
            $sms->reg($phone,$strs);

            if(!empty($phone)){
                echo  $code ;
            }
        }
    }
    public function phone()
    {
        $arr = input('param.');
        $phone = db('business')->where('bid',8)->field('phone,address')->find();
        if ($phone) {
            echo json_encode(['phone'=>$phone]);
        }
    }
    public function looktime ()
    {
        $arr = input('param.uid');
        $phone = db('user')->where('uid',$arr)->update(['looktime' => time()]);
        if ($phone) {
            echo json_encode(['code'=>1]);
        }
    }
    /**
     * 注册
     */
    public function add_pass(Request $request){
        $data = $request->get();
        $uid = $data['uid'];
        $phone = $data['phone'];
        $password = $data['password'];
        $bid = $data['bid'];
        $data = Db::name('user')->where('uid',$uid)->update(['phone'=> $phone,'password'=> $password,'bid'=> $bid ]);
        $this->jsonOut($data);
    }
    /**
     * 登录检测
     */
    public function checkLogin(Request $request){
        $data = $request->get();
        $uid = $data['uid'];
        $datas['bid'] = $data['bid'];
        $datas['phone'] = $data['phone'];
        $datas['password'] = $data['pwd'];
        $result = UserModel::instance()->checkLogin($datas);
        if($result){
//            Session::set('bus_bid',$result['bid']);
//            Session::set('bus_name',$map['name']);
            $res=Db::name('user')->where(['uid'=>$uid])->update(['login_status'=>1]);
            if($res){
                $result["code"]=1;
                $result['msg']="登录成功!";
                echo json_encode($result);//登录成功
            }
        }else{
            $result["code"]=0;
            $result['msg']="账号或密码错误!";
            echo json_encode($result);//登录失败
        }
    }
    /**
     * 重置密码
     */
    public function save_pass(Request $request){
        $uid=$request->get('uid');
        $phone=$request->get('phone');
        $pwd=$request->get('pwd');
        $data = Db::name('user')->where(['phone'=>$phone])->where(['uid'=>$uid])->update(['password'=>$pwd]);
        if($data){
            $result["code"]=1;
            $result['msg']="重置密码成功!";
            echo json_encode($result);
        }
    }
    /**
     *退出登录修改登录状态
     */
    public function login_status(Request $request){
        $data=$request->get();
        $uid = $data['uid'];
        $result=Db::name('user')->where('uid',$uid)->update(['login_status'=>0]);
        if($result){
            $data['code']=1;
            $data['msg']= '退出成功';
            echo json_encode($data);
        }
    }
    /*
     * 公司简介
     */
    public function jianjie(){
        $bid = $this->_getBid();
        $res = Db::name('business')->where('bid',$bid)->find();
        echo json_encode($res);die;
    }
    /**
     * 生成二维码
     */
    public function qrcode($uid,$bid){
//        $mess=Db::name('mess')->where(['bid'=>$bid])->find();
//        $accessToken=$mess['token'];
        $accessToken="10_8jhp0gvqsBO_X2OXVapHe2qofOT5-eTlqfSTEsOIVNXESWyCMqq9_USQdrhlkmGof9AGXgbvntUabOGP_3vkMkeVFU99lrSn9op351xuwClcRUXXvKKopK_YZPfVtID4j_8Qy2PQ01hm3i7xNAViAAAGTO";
        if(empty($accessToken)){
            $accessToken=$this->GetToken($bid);
        }
//        if(($mess['tokentime']+2000)<time()){
//            $accessToken=$this->GetToken($bid);
//        }
        //以上是获取token
        $data=json_encode([
            'scene'=>$uid,
            'width'=>450,
//            'page'=>'sd_liferuning/pages/constmer/index/index'
        ]);
        $url='https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$accessToken;
        $aurl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$accessToken}";
        if(json_decode(file_get_contents($aurl))->errcode==40001){
            $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$this->GetToken($bid)}";
        }
        $ch  = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $img = curl_exec($ch);
        var_dump($url);die;

        //生成二维码
        $filename=ROOT_PATH.'/public/uploads/qrcode/'.time().rand().'.jpg';
        $result=file_put_contents($filename,$img);
        if($result){
            $pic=db('haibao')->where('bid',$bid)->value('photo');
            $respic = substr($pic , 0 , 6);
            //获取拼接的图片
            $pic==''?$imgbgsrc=ROOT_PATH.'/public/uploads/111.jpg':$imgbgsrc=ROOT_PATH.'/public/uploads/business/'.$respic.'/'.$pic;
            $rs=$this->qrimg($filename,$imgbgsrc);
            if($rs){

                exit(json_encode(['code'=>1,'src'=>$rs]));
            }else{
                exit(json_encode(['code'=>0,'msg'=>'error']));
            }
        }
    }
    /**
     * @param $bid
     * @return bool
     * 获取GetToken
     */
    public function GetToken($bid){

        $loginId = Db::name('business')->where(['bid'=>$bid])->field('appid,secret')->find();
//var_dump($loginId);die;
        $data['grant_type']='client_credential';
        $data['appid']=$loginId['appid'];
        $data['secret'] = $loginId['secret'];
        $url='https://api.weixin.qq.com/cgi-bin/token?'.http_build_query ( $data );
var_dump($url);die;
        $ch  = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        $data = curl_exec($ch);
        $obj=json_decode($data);
        if(empty($obj->errcode)){
            $save['token']=$obj->access_token;
            $save['tokentime']=time();
            db('Mess')->where('bid',$bid)->update($save);
            return $obj->access_token;
        }else{
            return false;
        }
    }
    /**
     * @param $filename
     * @return bool
     * GD库拼接二维码
     * 将二维码和图片拼接在一起
     */
    public function qrimg($filename,$imgbgsrc){
        header('content-type:image/jpeg');
        $image=imagecreatefromjpeg($imgbgsrc);
        $qr=imagecreatefromjpeg($filename);
        $size=getimagesize($imgbgsrc);
        $width=$size[0];
        $height=$size[1];
        imagecopymerge($image, $qr, $width-450, $height-450, 0, 0, 450, 450,100);
        imagedestroy($qr);
        $name=time().mt_rand(1,1000);
        $qrname=ROOT_PATH.'/public/uploads/qrcode/'.$name.'.jpg';
        $rs=imagejpeg ($image,$qrname);
        imagedestroy($image);
        unlink($filename);

        if($rs){
            return config('uploadPath').'qrcode/'.$name.'.jpg';
        }else{
            return false;
        }
    }
}
